/***************************************************************************************
 * History
 * -------------------------------------------------------------------------------------
 * 04/02/2012	Removed warnings
 */
#include <stdio.h>
#include <avr/io.h>
#include <avr/wdt.h>
#include <util/delay.h>
#include <math.h>
#include <string.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include "backlight.h"
#include "lcd.h"
#include "pages.h"
#include "buttons.h"
#include "icon.h"
#include "can_avr.h"

//sub pages
#include "page1.h"
#include "diag.h"


uint8_t splashTimer = 0;
uint8_t currentPage = 0xff;
uint8_t activePage = 0;

extern const prog_uint8_t bmp_splash[];
extern const prog_uint8_t bmp_logo[];

typedef struct {
	void (*init)(void);
	void (*update)(void);
	bool (*buttons)(void);
	void (*clear)(void);
	bool updateIcons;
} stPage_t;

stPage_t pages[] = {
	{ &SPLASH_init, 	&SPLASH_update, 	NULL, 		&SPLASH_clear,		false	},
	{ &PAGE_1_init,		&PAGE_1_update,		NULL,		&PAGE_1_clear,		true	},
	{ &DIAG_1_init,		&DIAG_1_update,		NULL,		&DIAG_clear,		true	},
	{ &DIAG_2_init,		&DIAG_2_update,		NULL,		&DIAG_clear,		true 	},
};
#define PAGE_COUNT (sizeof(pages) / sizeof(stPage_t))

void SPLASH_init(void)
{
	LCD_Bitmap( (132 - 80) / 2, (170 - 82) / 2, bmp_splash );
}

void SPLASH_clear(void)
{
	LCD_Cls(0);
}

void SPLASH_update(void)
{
	//timeout on the splash screen
	splashTimer++;
	if( splashTimer > SPLASH_TIMEOUT ) {
		PAGE_set( 1 );
	}
}


void PAGE_set( uint8_t newScreen )
{
	//this buffers the update until the update process
	if( newScreen >= PAGE_COUNT ) {
		activePage = 0;
	}
	else {
		activePage = newScreen;
	}
	ICON_nextUpdateAll();
}


void PAGE_next( void )
{
	uint8_t i = activePage + 1;
	if( i >= PAGE_COUNT ) i = 1;
	PAGE_set( i );
}


void PAGE_handleButtons(void)
{
	if( pages[activePage].buttons == NULL ) {
		if( BUTTON_click(butPage, 25) ) {
			PAGE_next();
		}

	}
	else {
		if( pages[activePage].buttons() == false ) {
			if( BUTTON_click(butPage, 25) ) {
				PAGE_next();
			}
		}
	}
}


void PAGE_updateActive(void)
{
	if( activePage != currentPage ) {
		//we're going to change the page
		
		cli();		//stop being interrupted by trivial things!

		if( currentPage < PAGE_COUNT ) {
			if( pages[currentPage].clear != NULL ) {
				pages[currentPage].clear();
			}
		}

		if((activePage != 0) && (currentPage == 0)) {
			//icon for all the normal pages (1+)
			LCD_Bitmap( 0, 0, bmp_logo );
		}
		
		if( pages[activePage].init != NULL ) {
			pages[activePage].init();
		}
		
		currentPage = activePage;

		sei();		//turn on the interrupt again
	}
	
	if( pages[activePage].update != NULL ) {
		pages[activePage].update();
	}
}


void PAGE_updateIcons(void)
{
	if( activePage == currentPage ) {
		if( pages[currentPage].updateIcons ) ICON_update();
	}
}

